<template>
  <div>
    <Form ref="forms" inline :model="form" label-position="left" v-if="hasShow">
      <FormItem prop="date">
        <DatePicker
          :editable="false"
          type="daterange"
          :options="dateOptions"
          v-model="form.date"
          placeholder="请选择创建日期"
          @on-change="changeParams"
        />
      </FormItem>
      <FormItem prop="name">
        <Input
          clearable
          v-model="form.name"
          v-width="270"
          placeholder="请输入患者姓名/手机号/微信号/唯一身份"
          @on-enter="changeParamsKeyWord"
          @on-clear="changeParams"
        />
      </FormItem>
      <FormItem prop="status">
        <Select
          v-model="form.status"
          :max-tag-count="3"
          multiple
          placeholder="患者状态"
          clearable
          @on-change="changeParams"
        >
          <Option
            v-for="item in statusList"
            :value="item.value"
            :key="item.value"
            >{{ item.label }}</Option
          >
        </Select>
      </FormItem>
      <FormItem prop="last_callback_id">
        <Select
          v-model="form.last_callback_id"
          :max-tag-count="3"
          multiple
          placeholder="上次回访人"
          clearable
          @on-change="changeParams"
        >
          <OptionGroup
            :label="item.label"
            v-for="(item, index) in personnelList"
            :key="index"
          >
            <Option
              :value="itemTwo.value"
              v-for="(itemTwo, indexTwo) in item.children"
              :key="indexTwo.value"
              >{{ itemTwo.label }}</Option
            >
          </OptionGroup>
        </Select>
      </FormItem>
      <FormItem prop="personnel">
        <!-- <Select :max-tag-count="3" v-model="form.personnel" multiple placeholder="请选择归属人" clearable
          @on-change="changeParams">
          <OptionGroup :label="item.label" v-for="(item, index) in personnelList" :key="index">
            <Option :value="itemTwo.value" v-for="(itemTwo, indexTwo) in item.children" :key="indexTwo.value">{{
              itemTwo.label }}</Option>
          </OptionGroup>
        </Select> -->
        <searchTree
          :multiple="true"
          :options="belongData"
          placeholder="归属人"
          :limit="3"
          :normalizer="normalizer"
          @input="valueChange"
          :limitText="limitText"
          noResultsText="无数据"
        />
      </FormItem>
      <FormItem prop="disease">
        <TreeSelect
          :max-tag-count="3"
          placeholder="请选择病种"
          v-model="form.disease"
          :data="diseaseList"
          filterable
          multiple
          @on-change="changeParams"
        />
      </FormItem>
      <FormItem prop="channel">
        <Select
          filterable
          :max-tag-count="3"
          multiple
          v-model="form.channel"
          placeholder="请选择渠道来源"
          @on-change="changeParams"
        >
          <OptionGroup
            :label="item.label"
            v-for="(item, index) in channelList"
            :key="index"
          >
            <Option
              :value="itemTwo.value"
              v-for="(itemTwo, indexTwo) in item.children"
              :key="indexTwo.value"
              >{{ itemTwo.label }}</Option
            >
          </OptionGroup>
        </Select>
      </FormItem>
      <FormItem prop="tag">
        <TreeSelect
          :max-tag-count="3"
          v-model="form.tag"
          :data="partList"
          placeholder="请选择部位"
          multiple
          @on-change="changeParams"
        />
      </FormItem>
      <FormItem prop="city" v-if="view_info.type === 0">
        <!-- <Select v-width="110" v-model="form.city" placeholder="请输入城市" filterable remote clearable
          :remote-method="remoteMethod" :loading="loadingCity" @on-change="changeParams">
          <Option v-for="(item, index) in cityList" :key="index" :value="item.value" :label="item.label">
            {{ item.label }}
          </Option>
        </Select> -->
        <div style="margin-top:2px"></div>
        <jgcheckcity
          ref="checkcity"
          @cityvalue="cityvalue"
          v-model="city_id"
          name="improvePlan"
        />
      </FormItem>
      <FormItem prop="wx">
        <Select
          v-width="130"
          v-model="form.wx"
          placeholder="请选择电话"
          clearable
          @on-change="changeParams"
        >
          <Option
            v-for="item in hasPhone"
            :value="item.value"
            :key="item.value"
            >{{ item.label }}</Option
          >
        </Select>
      </FormItem>
      <FormItem prop="phone">
        <Select
          v-width="130"
          v-model="form.phone"
          placeholder="请选择微信"
          clearable
          @on-change="changeParams"
        >
          <Option v-for="item in hasWx" :value="item.value" :key="item.value">{{
            item.label
          }}</Option>
        </Select>
      </FormItem>
      <FormItem
        v-hasC="{
          name: 'v1-data-view-move',
          flag: 'v1/data/view/move',
        }"
      >
        <Button
          v-if="view_info.type === 0"
          @click.native="handleContextMenuEdit"
          type="primary"
          :disabled="disabledChange"
          >批量切换</Button
        >
        <Button
          style="margin-left:10px"
          @click="handleMultipleTag"
          type="primary"
          :disabled="disabledChange || form.phone !== 1"
          :loading="tagLoading"
          >批量微信标签</Button
        >
      </FormItem>
    </Form>
    <Modal
      :mask-closable="false"
      title="批量添加微信标签"
      width="518"
      v-model="multipleTag"
      @on-cancel="cancelTagModal"
    >
      <Form :labelWidth="118">
        <FormItem label="已选人数：">{{ tagWechatNumObj.total }}</FormItem>
        <FormItem label="可添加人数：">
          {{ tagWechatNumObj.bind_total
          }}<Tooltip
            max-width="200"
            content="未绑定微信的患者不可同步添加微信标签"
          >
            <Icon class="ivu-ml-8" type="md-help-circle" />
          </Tooltip>
        </FormItem>
        <FormItem label="录入标签：">
          <Input
            v-model="tagName"
            show-word-limit
            maxlength="10"
            placeholder="请输入标签名称"
          />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="cancelTagModal">取消</Button>
        <Button
          type="primary"
          @click="confirmChangeTag"
          :loading="changingLoadingTag"
          >确定</Button
        >
      </div>
    </Modal>
    <Modal
      @on-cancel="cancel"
      v-model="cutView"
      width="360"
      title="切换患者视图"
      :mask-closable="false"
    >
      <Select v-model="changeViewId">
        <Option
          v-for="item in filterView"
          :key="item.vaule"
          :value="item.value"
        >
          {{ item.title }}
        </Option>
      </Select>
      <div slot="footer">
        <Button @click="cancel">取消</Button>
        <Button
          type="primary"
          @click="confirmChangeView('change')"
          :loading="changingLoading"
          >确定</Button
        >
      </div>
    </Modal>
    <div style="margin-bottom: 8px;">
      <a
        v-if="view_info.type === 0 && !twoStatus"
        :disabled="pageParams.total === 0"
        @click="handleSelectAll"
        >{{ !selectStatus ? "一键全选" : "一键取消" }}</a
      >
      <a v-if="view_info.type === 0 && twoStatus" @click="handleSelectAlls"
        >一键取消</a
      >
      <span style="color:#ccc;margin-left:15px"
        >已选中：{{ hasSelectLength }}条</span
      >
    </div>
    <Table
      ref="table"
      :columns="columns1"
      :data="tableData"
      :max-height="580"
      :loading="loading"
      @on-selection-change="changeCheckBox"
      @on-sort-change="sortChange"
    >
      <template slot="basic" slot-scope="{ row }">
        <a @click="handleDetailPatient(row)"
          >{{ row.user_name }}<span class="ivu-ml-8">{{ row.age }}</span
          ><span class="ivu-ml-8"> {{ row.gender_str }}</span></a
        >
      </template>
      <template slot="realname" slot-scope="{ row }">
        <span>{{ +row.patient_data_type === 0 ? row.realname : "" }}</span>
      </template>
      <template slot="diseases_name" slot-scope="{ row }">
        {{ row.child_diseases_name || row.diseases_name }}
      </template>
      <template slot="state" slot-scope="{ row }">
        <Tag v-if="row.status_name === '无效'" color="red">{{
          row.status_name
        }}</Tag>
        <Tag v-else-if="row.status_name === '跟进中'" color="volcano">{{
          row.status_name
        }}</Tag>
        <Tag v-else-if="row.status_name === '预约'" color="cyan">{{
          row.status_name
        }}</Tag>
        <Tag v-else-if="row.status_name === '到诊'" color="green">{{
          row.status_name
        }}</Tag>
        <Tag v-else-if="row.status_name === '老患者到诊'" color="magenta">{{
          row.status_name
        }}</Tag>
        <Tag v-else-if="row.status_name === '有意向'" color="blue">{{
          row.status_name
        }}</Tag>
        <Tag v-else-if="row.status_name === '未开口'" color="purple">{{
          row.status_name
        }}</Tag>
        <Tag v-else-if="row.status_name" color="orange">{{
          row.status_name
        }}</Tag>
      </template>
      <template slot="city" slot-scope="{ row }">
        {{ row.city_name }}
      </template>
      <template slot="action" slot-scope="{ row }">
        <a
          v-hasC="{
            name: 'v1-patient-index-update5',
            flag: 'v1/patient/index/update',
          }"
          @click="handleOpenDrawer(row)"
          >编辑</a
        >
        <Divider
          v-hasCC="[
            {
              name: 'v1-patient-index-update5',
              flag: 'v1/patient/index/update',
            },
            {
              name: 'v1-patient-callback-create',
              flag: 'v1/patient/callback/create',
            },
          ]"
          type="vertical"
        />
        <a
          v-hasC="{
            name: 'v1-patient-callback-create',
            flag: 'v1/patient/callback/create',
          }"
          @click="handleReturnVisit(row, row.id)"
          >回访</a
        >
        <Divider
          v-hasCC="[
            {
              name: 'v1-patient-callback-hidden',
              flag: 'v1/patient/callback/hidden',
            },
          ]"
          v-if="view_info.id > 0 && +view_info.type === 0"
          type="vertical"
        />
        <a
          v-hasC="{
            name: 'v1-patient-callback-hidden',
            flag: 'v1/patient/callback/hidden',
          }"
          v-if="view_info.id > 0 && +view_info.type === 0"
          @click="handleHidden(row, row.id)"
          >隐藏</a
        >
      </template>
    </Table>
    <div class="ivu-mt ivu-text-center">
      <Page
        :page-size-opts="pageSizeOp"
        :total="pageParams.total"
        :current="pageParams.page"
        show-total
        show-sizer
        show-elevator
        :page-size="pageParams.pageSize"
        @on-change="handleChangePage"
        @on-page-size-change="handleChangePageSize"
      />
    </div>
    <patient-detail
      :btnShow="btnShow"
      ref="patientDetail"
      @cancelDrawer="resetAll"
      :viewInfo="view_info"
    />
    <edit-patient ref="editPatient" @patientfun="resetAll" />
    <return-visit
      ref="returnVisit"
      @patientfuns="_getViewData"
      :id="id"
      :tabList="tabList"
      :viewInfo="view_info"
      @changeNum="changeNum"
      :isCallBack="isCallBack"
    />
  </div>
</template>
<script>
import tableList from "./table-list";
// import jgcheckcity from "@/components/checkcity";
import editPatient from "@/components/editPatient";
import patientDetail from "@/components/patientDetail";
import returnVisit from "@/components/returnVisit";
import {
  getViewData,
  changeView,
  deleteViewData,
  wxIdNumDetail,
  tagNameDetail,
  viewHidden,
} from "../../../api/TApi/index.js";
import { patientindexsearchcity } from "../../../api/hqapi/index.js";
import { mapState, mapMutations } from "vuex";
import searchTree from "@riophae/vue-treeselect";
export default {
  components: {
    tableList,
    editPatient,
    patientDetail,
    returnVisit,
    searchTree,
  },
  props: {
    id: {
      // 视图类型id
      type: [Number, String],
      require: true,
    },
    tabList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      tagLoading: false,
      tagName: "",
      wechatid: [],
      name: "view",
      orderType: {
        callback_count: "sort_callback_count",
        next_callback_time_str: "sort_last_callback_time",
        created_at_str: "sort_created_at",
      },
      order: {
        sort_callback_count: 0,
        sort_last_callback_time: 0,
        sort_created_at: 0,
      },
      hasShow: true,
      changeType: "",
      changeViewId: "",
      changingLoading: false,
      // 内部按钮权限传递到子组件控制显示隐藏
      btnShow: [
        {
          name: "v1-patient-index-sub3",
          flag: "v1/patient/index/sub",
        },
        {
          name: "v1-patient-index-edit-remark3",
          flag: "v1/patient/index/edit-remark",
        },
        {
          name: "v1-patient-index-update6",
          flag: "v1/patient/index/update",
        },
        {
          name: "v1-patient-callback-callback-common-list3",
          flag: "v1/patient/callback/callback-common-list",
        },
        {
          name: "v1-patient-index-edit-tags5",
          flag: "v1/patient/index/edit-tags",
        },
        {
          name: "v1-patient-index-edit-tags6",
          flag: "v1/patient/index/edit-tags",
        },
      ],
      changingLoadingTag: false,
      selectItemArr: [], //全选反选的数据
      loading: false,
      outPatientIds: [], //全选的时候排除的患者id
      pageSizeOp: [10, 20, 30, 40, 50],
      columns1: [],
      columns2: [
        {
          type: "selection",
          width: 60,
          fixed: "left",
        },
        {
          title: "基本信息",
          show: true,
          slot: "basic",
          minWidth: 150,
          fixed: "left",
        },
        {
          title: "归属视图",
          key: "view_title",
          minWidth: 150,
        },
        {
          title: "患者状态",
          show: true,
          slot: "state",
          minWidth: 150,
        },
        {
          title: "回访次数",
          key: "callback_count",
          sortable: "custom",
          show: true,
          minWidth: 118,
        },
        {
          title: "上次回访时间",
          key: "last_callback_time_str",
          show: true,
          minWidth: 158,
        },
        {
          title: "上次回访人",
          key: "last_callback_realname",
          show: true,
          minWidth: 118,
        },
        {
          title: "待回访时间",
          key: "next_callback_time_str",
          sortable: "custom",
          show: true,
          minWidth: 125,
        },
        // {
        //     title: '微信标签',
        //     key: 'label',
        //     slot: 'label',
        //     show: true,
        //     minWidth: 138
        // },
        {
          title: "城市",
          slot: "city",
          show: true,
          minWidth: 100,
        },
        {
          title: "病种",
          slot: "diseases_name",
          show: true,
          minWidth: 100,
        },
        {
          title: "来源",
          minWidth: 100,
          show: true,
          key: "source_name",
        },
        {
          title: "归属人",
          slot: "realname",
          show: true,
          minWidth: 100,
        },
        {
          title: "创建时间",
          key: "created_at_str",
          show: true,
          minWidth: 160,
          sortable: "custom",
        },
        {
          title: "备注",
          minWidth: 150,
          tooltip: true,
          show: true,
          key: "remark",
        },
        {
          title: "操作",
          width: 160,
          show: true,
          slot: "action",
          fixed: "right",
        },
      ],
      tagWechatNumObj: {},
      cityList: [],
      pageParams: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      view_info: {}, //试图类型
      multipleTag: false,
      cutView: false,
      tableData: [],
      form: {
        name: "", //搜索关键字
        date: "", //日期
        city: "",
        personnel: [], //归属人
        last_callback_id: [],
        status: [], //患者状态
        disease: [], //病种
        channel: [], //渠道来源 【多个用','分割】
        tag: [], //请选择部位 【多个用','分割】
        wx: "", //是否有微信
        phone: "", //是否有电话
      },
      statusList: [], //患者状态列表
      hasPhone: [
        {
          value: 1,
          label: "有电话",
        },
        {
          value: 2,
          label: "无电话",
        },
      ], //电话列表
      hasWx: [
        {
          value: 1,
          label: "有微信",
        },
        {
          value: 2,
          label: "无微信",
        },
      ], //微信列表
      diseaseList: [], //病种列表
      twoStatus: false,
      channelList: [], //渠道来源列表
      personnelList: [], //归属人列表
      partList: [], //选择部位列表
      loadingCity: false,
      contextLine: "",
      isCallBack: {},
      city_id: [],
      // 限制时间范围
      dateOptions: {},
      shortcuts: [
        {
          text: "今天",
          value: () => {
            const date = this.$Date(new Date()).format("YYYY-MM-DD");
            return [date, date];
          },
        },
        {
          text: "昨天",
          value: () => {
            let date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            date = this.$Date(date).format("YYYY-MM-DD");
            return [date, date];
          },
        },
        {
          text: "本周",
          value: () => {
            const date = new Date();
            const start = this.$Date(date)
              .day(1)
              .format("YYYY-MM-DD");
            const end = this.$Date(date)
              .day(7)
              .format("YYYY-MM-DD");
            return [start, end];
          },
        },
        {
          text: "本月",
          value: () => {
            const date = new Date();
            const start = this.$Date(date)
              .date(1)
              .format("YYYY-MM-DD");
            const end = this.$Date(date)
              .add(1, "month")
              .date(1)
              .subtract(1, "day")
              .format("YYYY-MM-DD");
            return [start, end];
          },
        },
      ],
      selectStatus: false,
      belongData: [],
      belongValue: [],
      normalizer(node) {
        return {
          id: node.value,
          label: node.label,
          children: node.children,
        };
      },
      limitText: function(count) {
        return `+ ${count}`;
      },
    };
  },
  created() {
    this.columns1 = this.columns2;
    if (this.id !== 0) {
      this.columns1.splice(2, 1);
    }
    this._getViewData();
  },
  watch: {
    wsIsConnect: {
      handler(value) {
        // console.log(value, 1111);
      },
      deep: true,
      immediate: true,
    },
    outPatientIds: {
      handler(value) {
        let idArr = [];
        value.forEach((ee) => {
          if (ee.data.length) {
            for (let i in ee.data) {
              idArr.push(ee.data[i]);
            }
          }
        });
        if (idArr.length === this.pageParams.total) {
          this.selectStatus = false;
        }
      },
      deep: true,
    },
    selectItemArr: {
      handler(value, oldValue) {
        if (value.length === this.pageParams.total) {
          this.twoStatus = true;
        } else if (value.length === 0) {
          this.twoStatus = false;
        }
      },
    },
  },
  computed: {
    ...mapState("power/export", ["wsIsConnect"]),
    disabledChange() {
      if (this.selectStatus) {
        return false;
      } else {
        return this.selectItemArr.length ? false : true;
      }
    },
    filterView() {
      return this.tabList.filter((ee) => ee.id !== this.id && ee.type === "0");
    },
    hasSelectLength: {
      get() {
        if (this.selectStatus) {
          let idArr = [];
          this.outPatientIds.forEach((ee) => {
            if (ee.data.length) {
              for (let i in ee.data) {
                idArr.push(ee.data[i]);
              }
            }
          });
          this.logs(1, this.pageParams.total - idArr.length);
          return this.pageParams.total - idArr.length;
        } else {
          this.logs(2, this.selectItemArr.length);
          return this.selectItemArr.length;
        }
      },
    },
  },
  methods: {
    cityvalue(city) {
      this.city_id = city;
      this.pageParams.page = 1;
      this.form.city = city.join(",");
      this._getViewData();
    },
    handleSelectAlls() {
      this.outPatientIds = [];
      this.selectItemArr = [];
      this.$refs.table.selectAll(false);
      this.twoStatus = false;
    },
    handleSelectAll() {
      this.outPatientIds = [];
      this.selectItemArr = [];
      if (this.selectStatus) {
        this.selectStatus = false;
        this.$refs.table.selectAll(false);
      } else {
        this.selectStatus = true;
        this.$refs.table.selectAll(true);
      }
    },
    remoteMethod(query) {
      if (query !== "") {
        let reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
        if (!reg.test(query)) {
          return;
        }
        this.loadingCity = true;
        patientindexsearchcity({ keywords: query }).then((res) => {
          this.cityList = res.list;
          this.loadingCity = false;
        });
      }
    },
    resetAll() {
      this._getViewData();
      this.$refs.editPatient.closeDrawer();
      this.$emit("editChangeTotal", this.id);
    },
    sortChange(params) {
      let { key, order } = params;
      for (let keys in this.order) {
        this.order[keys] = 0;
      }
      switch (order) {
        case "normal":
          {
          }
          break;
        case "asc":
          {
            this.order[this.orderType[key]] = 1;
          }
          break;
        case "desc":
          {
            this.order[this.orderType[key]] = 2;
          }
          break;
      }
      this._getViewData();
    },
    changeNum(data) {
      this.$emit("changeTabNum");
    },
    cancelTagModal() {
      this.tagName = "";
      this.multipleTag = false;
    },
    cancel() {
      this.changeViewId = "";
      this.cutView = false;
    },
    confirmChangeTag() {
      if (this.tagName) {
        this.changingLoadingTag = true;
        tagNameDetail({ tag_name: this.tagName }).then((res) => {
          this.wechatid.forEach((ee) => {
            // if (ee.is){
            let params = {
              MsgType: "ContactLabelTask",
              Content: {
                WeChatId: ee,
                LabelName: this.tagName,
                LabelId: res[ee] ? (res[ee].tag_id ? res[ee].tag_id : 0) : 0,
                AddList: this.tagWechatNumObj.friendid.join(","),
                taskId: new Date().getTime() + parseInt(Math.random() * 10000),
              },
            };
            if (this.wsIsConnect) {
              this.$websocket.sendSock(params);
              this.multipleTag = false;
            } else {
              this.$Message.error("ws未连接上");
            }
            // }
          });
          this.tagName = "";
          this.changingLoadingTag = false;
        });
      } else {
        this.$Message.warning("请先录入标签");
      }
    },
    // 确定切换视图按钮
    confirmChangeView(type) {
      // if (this.changeViewId) {
      return new Promise((resolve, reject) => {
        let params;
        if (!this.selectStatus) {
          //非全选状态直接驱取绑定的数组
          params = {
            id: this.id, //本视图id
            move_id: this.changeViewId ? this.changeViewId : 0, //被移动到的视图id
            patient_user_id: this.selectItemArr.join(","),
            is_all: 0,
          };
        } else {
          //全选状态取排除再外的id集合
          let idArr = [];
          this.outPatientIds.forEach((ee) => {
            if (ee.data.length) {
              for (let i in ee.data) {
                idArr.push(ee.data[i].id);
              }
            }
          });
          params = {
            id: this.id, //本视图id
            move_id: this.changeViewId ? this.changeViewId : 0, //被移动到的视图id
            is_all: 1,
            not_user_id: idArr.join(","),
          };
        }
        params.start_time = this.form.date[0]
          ? this.$Date(this.form.date[0]).format("YYYY-MM-DD")
          : ""; //创建开始时间【格式：2020-01-01】
        params.end_time = this.form.date[1]
          ? this.$Date(this.form.date[1]).format("YYYY-MM-DD")
          : ""; //创建开始时间【格式：2020-01-01】
        params.patient_status_id = this.form.status.join(","); //患者状态
        params.belong_member_id = this.form.personnel.join(","); //归属人
        params.last_callback_id = this.form.last_callback_id.join(","); //归属人
        params.patient_diseases_id = this.form.disease.join(","); //一级病种ID
        params.channel_id = this.form.channel.join(","); //来源渠道ID【多个用','分割】
        params.body_parts_id = this.form.tag.join(","); //部位ID【多个用','分割】
        params.have_mobile = this.form.wx ? this.form.wx : 0; //是否绑定手机号【0默认、1是、2否】
        params.have_wechat = this.form.phone ? this.form.phone : 0; //是否绑定微信号【0默认、1是、2否】
        params.area_code = this.form.city;
        switch (
          type //切换视图操作
        ) {
          case "change":
            {
              this.changingLoading = true;
              changeView(params)
                .then((res) => {
                  this.$Message.success("切换成功");
                  this.cutView = false;
                  this.selectStatus = false;
                  this.outPatientIds = [];
                  this.selectItemArr = [];
                  this.pageParams.page = 1;
                  this._getViewData();
                  this.$emit("changeTabNum");
                  // 在改变父组件tab的数量后在制空
                  this.changeViewId = "";
                })
                .finally(() => {
                  this.changingLoading = false;
                });
            }
            break;
          case "numDetail":
            {
              delete params.move_id;
              //微信打标签之前先查询绑定人数
              wxIdNumDetail(params).then((res) => {
                resolve(res);
              });
            }
            break;
        }
      });
    },
    // 在多选模式下有效，只要选中项发生变化时就会触发
    changeCheckBox(arr) {
      if (this.selectStatus) {
        // 全选状态下
        let selectPatientIdArr = arr.map((ee) => ee.id); //将所有选中的id拿出来
        let currentPageAllPatientId = this.tableData.map((ee) => {
          return {
            id: ee.id,
            weChatId: ee.wechat_id,
          };
        }); //将当前页数据的id拿出来
        //difference为筛选出当前页不包含被选中的id集合
        let difference = currentPageAllPatientId.filter((x) => {
          return selectPatientIdArr.indexOf(x.id) === -1;
        });
        //创建对象page，为当前页码，data为未被选中得数据集合，后面在某一页直接取消单个选中或者其他操作，只要是在一键选中状态得直接替换，不需要单个排除做筛选
        let onePageData = {
          page: this.pageParams.page,
          data: difference,
        };
        //寻找总集合里面是否已经包含当前页得操作
        let indexHas = this.outPatientIds.findIndex(
          (ee, index) => ee.page === this.pageParams.page
        );
        if (indexHas !== -1) {
          //存在直接替换
          this.$set(this.outPatientIds, indexHas, onePageData);
        } else {
          //不存在直接插入
          this.outPatientIds.push(onePageData);
        }
      } else {
        //非全选状态下
        this.selectItemArr = arr.map((ee) => ee.id);
      }
      // console.log(selectPatientIdArr, currentPageAllPatientId)
    },
    //回访
    handleReturnVisit(row, id) {
      this.isCallBack = row;
      this.$refs.returnVisit.handleReturnVisit(id, row);
    },
    handleHidden(row, id) {
      this.$Modal.confirm({
        title: "隐藏提示",
        content: "<p>是否将患者从本视图隐藏</p>",
        onOk: () => {
          viewHidden({ patient_user_id: id, id: this.view_info.id }).then(
            () => {
              this._getViewData();
              this.$emit("changeTabNum");
              this.$Message.success("隐藏成功");
            }
          );
        },
      });
    },
    // 点击基本信息操作
    handleDetailPatient(row) {
      this.$refs.patientDetail.handleOpen(row);
    },
    // 编辑患者
    handleOpenDrawer(row) {
      if (+row.patient_data_type !== 0) {
        this.$refs.editPatient.handleEdit(row, true);
      } else {
        this.$refs.editPatient.handleEdit(row);
      }
    },
    // 切换页码
    handleChangePage(page) {
      this.pageParams.page = page;
      this._getViewData();
    },
    // 切换每页条数
    handleChangePageSize(size) {
      this.pageParams.page = 1;
      this.pageParams.pageSize = size;
      this._getViewData();
    },
    resetForm() {
      let name = this.form.name;
      this.form = {
        name, //搜索关键字
        date: [], //日期
        personnel: [], //归属人
        last_callback_id: [],
        city: "",
        status: [], //患者状态
        disease: [], //病种
        channel: [], //渠道来源 【多个用','分割】
        tag: [], //请选择部位 【多个用','分割】
        wx: 0, //是否有微信
        phone: 0, //是否有电话
      };
    },
    changeParamsKeyWord() {
      if (this.form.name) {
        this.pageParams.page = 1;
        this.resetForm();
        this._getViewData();
      }
    },
    _getViewData() {
      let params;
      if (this.form.name) {
        params = {
          id: this.id, //视图ID
          start_time: "", //创建开始时间【格式：2020-01-01】
          end_time: "", //创建结束时间【格式：2020-01-01】
          keywords: this.form.name, //关键词【姓名or手机号】
          patient_status_id: "", //患者状态
          belong_member_id: [], //归属人
          last_callback_id: [], //上次归属人
          patient_diseases_id: "", //一级病种ID
          channel_id: "", //来源渠道ID【多个用','分割】
          body_parts_id: "", //部位ID【多个用','分割】
          have_mobile: "", //是否绑定手机号【0默认、1是、2否】
          have_wechat: "", //是否绑定微信号【0默认、1是、2否】
          page: this.pageParams.page, //
          city_id: "",
          pageSize: this.pageParams.pageSize, //
          ...this.order,
        };
      } else {
        params = {
          id: this.id, //视图ID
          start_time: this.form.date[0]
            ? this.$Date(this.form.date[0]).format("YYYY-MM-DD")
            : "", //创建开始时间【格式：2020-01-01】
          end_time: this.form.date[1]
            ? this.$Date(this.form.date[1]).format("YYYY-MM-DD")
            : "", //创建结束时间【格式：2020-01-01】
          keywords: "", //关键词【姓名or手机号】
          patient_status_id: this.form.status.join(","), //患者状态
          belong_member_id: this.belongValue.join(","), //归属人
          last_callback_id: this.form.last_callback_id.join(","), //上次归属人
          patient_diseases_id: this.form.disease.join(","), //一级病种ID
          channel_id: this.form.channel.join(","), //来源渠道ID【多个用','分割】
          body_parts_id: this.form.tag.join(","), //部位ID【多个用','分割】
          have_mobile: this.form.wx ? this.form.wx : 0, //是否绑定手机号【0默认、1是、2否】
          have_wechat: this.form.phone ? this.form.phone : 0, //是否绑定微信号【0默认、1是、2否】
          page: this.pageParams.page, //
          area_code: this.form.city,
          pageSize: this.pageParams.pageSize, //
          ...this.order,
        };
      }
      this.loading = true;
      getViewData(params)
        .then((res) => {
          this.pageParams.total = res.total;
          if (res.condition.start_time || res.condition.end_time) {
            this.dateOptions = {
              disabledDate(date) {
                let startTime = res.condition.start_time
                  ? new Date(res.condition.start_time).valueOf()
                  : "";
                let endTime = res.condition.end_time
                  ? new Date(res.condition.end_time).valueOf()
                  : "";
                return (
                  date &&
                  (date.valueOf() < startTime.valueOf() ||
                    date.valueOf() > endTime.valueOf())
                );
              },
              shortcuts: [],
            };
          } else {
            this.dateOptions = {
              shortcuts: this.shortcuts,
            };
          }
          // 如果第一次进来复制过了，在筛选条件时二次赋值
          if (!this.partList.length) this.partList = res.condition.body_parts;
          if (!this.diseaseList.length)
            this.diseaseList = res.condition.diseases;
          if (!this.statusList.length)
            this.statusList = res.condition.patient_status;
          if (!this.channelList.length)
            this.channelList = res.condition.source_channel;

          if (!this.personnelList.length) {
            this.personnelList = res.condition.member_list;
            this.belongData = JSON.parse(
              JSON.stringify(res.condition.member_list)
            );
          }
          this.view_info = res.view_info;
          this.wechatid = res.wechatid;
          this.tableData = Object.freeze(res.list);
          if (this.selectStatus) {
            this.$nextTick(() => {
              let currentNoSelectData = this.outPatientIds.find(
                (ee) => ee.page === this.pageParams.page
              );
              //currentNoSelectData看之前是否存过当前页得数据并且进行过操作，回了操作后回显，如果操作过，将上次对当前页面得操作未选中得数据，在当前得checkBox不被选中显示
              //如果操作过走if，如果没操作过并且是一键选中状态走else
              if (currentNoSelectData && currentNoSelectData.data) {
                let filterArr = this.tableData.map((ee) => {
                  return {
                    ...ee,
                    _checked: currentNoSelectData.data.find(
                      (aa) => aa.id === ee.id
                    )
                      ? false
                      : true,
                  };
                });
                this.tableData = filterArr;
              } else {
                this.$refs.table.selectAll(true);
              }
            });
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    changeParams() {
      // console.log(this.form)
      this.pageParams.page = 1;
      this._getViewData();
      this.outPatientIds = [];
      this.selectItemArr = [];
    },
    handleContextMenuEdit() {
      this.cutView = true;
    },
    handleContextMenu(row) {
      this.contextLine = row.id;
    },
    handleMultipleTag() {
      this.tagLoading = true;
      this.confirmChangeView("numDetail")
        .then((res) => {
          this.tagWechatNumObj = res;
          this.multipleTag = true;
        })
        .finally(() => {
          this.tagLoading = false;
        });
    },
    handleContextMenuDelete() {
      this.$Modal.confirm({
        title: "移除提示",
        content: "是否将患者从本视图移除",
        okText: "确定",
        loading: true,
        onOk: () => {
          deleteViewData({
            id: this.id,
            patient_user_id: this.contextLine,
          })
            .then((res) => {
              this.$Message.success("移除成功");
              this.$emit("changeTabNum", {
                type: "three",
                id1: this.id,
                num1: 1,
              });
              this._getViewData();
            })
            .finally(() => {
              this.$Modal.remove();
            });
        },
      });
    },

    valueChange(e) {
      this.belongValue = [];
      e.forEach((item) => {
        let flag = true;
        this.belongData.forEach((ele) => {
          if (ele.value == item) {
            flag = false;
            ele.children.forEach((id) => {
              this.belongValue.push(id.value);
            });
          }
        });
        if (flag) {
          this.belongValue.push(item);
        }
      });
      this.changeParams();
    },
  },
  mounted() {
    let ProjectId = localStorage.getItem("currentProject");
    let ProjectCity = JSON.parse(localStorage.getItem("project"));
    for (let item of ProjectCity) {
      if (+ProjectId === +item.project_id && item.city_name !== "") {
        this.cityList = [
          {
            key: item.default_city,
            value: item.default_city,
            label: item.city_name,
          },
        ];
      }
    }
  },
};
</script>
<style lang="less">
.colname {
  margin-bottom: 8px;
}

.vue-treeselect__control {
  height: 32px;
}
.vue-treeselect__control {
  min-width: 150px;
  width: auto;
  line-height: 14px;
}
</style>
